package com.chen.base.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

/**
 * @Title:多数据源配置
 * @Description: 主要数据源
 * @Author: chenjiwei
 * @Date: 2020-10-31 0:45
 * @Version: 1.0.0
 */
@Configuration
@EnableJpaRepositories(
        basePackages = "com.chen.dao",
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager"
)
public class DatabaseConfig {
    @Autowired
    @Qualifier("testDataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("testJpaProperties")
    private JpaProperties testJpaProperties;

    @Bean(name = "entityManager")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return entityManagerFactory(builder).getObject().createEntityManager();

    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder){
        return builder.dataSource(dataSource)
                .properties(testJpaProperties.getProperties())
                .persistenceUnit("persistenceUnit")
                .packages("com.chen.entity")
                .build();

    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(entityManagerFactory(builder).getObject());
    }
}
